﻿using FastBuild;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Hosting.WindowsServices;
using System.Net;

var options = new WebApplicationOptions
{
    Args = args,
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default
};

var builder = WebApplication.CreateBuilder(options);

builder.Host.UseWindowsService();

builder.FastBuild(
(option, configuration) =>
{
    option.UseTimeJob()
    .Configure(app =>
    {
        app.MapGet("/IISRestart", (string callback, ILog log) =>
        {
            Console.WriteLine(callback);
            Console.WriteLine(DateTime.Now);
            log.Info($"callback:{callback}，DateTime:{DateTime.Now}", "IISRestart");

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(10000);
                //重启10次 不行记录错误日志
                int restartCount = 1;
                var httpclient = new HttpClient();
                var clientReturn = httpclient.GetAsync(callback).Result;
                while (clientReturn.StatusCode != HttpStatusCode.OK && restartCount < 10)
                {
                    Thread.Sleep(5000);
                    clientReturn = httpclient.GetAsync(callback).Result;
                    if (clientReturn.StatusCode != HttpStatusCode.OK)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine($"IIS ReStart for the {restartCount} time,Status Code:{clientReturn.StatusCode}");
                        log.Info($"IIS ReStart for the {restartCount} time,Status Code:{clientReturn.StatusCode}", "IISRestart");
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                    restartCount++;
                }
                if (clientReturn.StatusCode != HttpStatusCode.OK)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine($"IIS Can't ReStart Success，DateTime:{DateTime.Now}");
                    log.Info($"IIS Can't ReStart Success，DateTime:{DateTime.Now}", "IISRestart");
                    Console.ForegroundColor = ConsoleColor.White;
                }
                else
                {
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine($"IIS ReStart Success，DateTime:{DateTime.Now}");
                    log.Info($"IIS ReStart Success，DateTime:{DateTime.Now}", "IISRestart");
                    Console.ForegroundColor = ConsoleColor.White;
                }
                clientReturn.Dispose();
                httpclient.Dispose();
            });
        });
    });
}).Run();